#
# Ph::Controller
#

module Ph

	class Controller

		# controller should define @data with the Table/Query from where to pull the data.
		def initialize
			self.setup()
		end

		def request(env)
			@env = env
			@driver = @data.database.connect

			method = env['REQUEST_METHOD']
			self.respond_to?(method) ? self.send(method) : [400]
		end

		def is_int?(str)
			str =~ /d+/
		end

		#
		# Returns Hash with parameter information
		#
		def parse_parameters
			return [] if @env[:parameters].empty?

			params = @env[:parameters]
			result = Hash.new

			if is_int? params[0] then
				result['id'] = params[0]
				i = 1
			else
				i = 0
			end

			while(params[i]) do
				result[params[i]] = params[i+1] if params[i+1]
				i += 2
			end

			result
		end
		
		# HTTP METHODS

		def self.implement_method *method

			method.each do |m|
				case m
				when :head
					class_eval %{
						def HEAD
							[200, {'Ph-Data-Info' => @data.record.to_json}]
						end
					}
				when :get
					class_eval %{
						def GET
							where = []
							parse_parameters.each do |k, v|
								where << k + '=' + v
							end
							
							result = @driver.select(@data, where.empty? ? nil : where.join(' AND '))
							[200, {'Content-Type' => 'application/json'}, result]
						end
					}
				when :post
					class_eval %{
						def POST
							postdata = @env['rack.input']
							@driver.insert(@data, postdata)

							[200, {'Content-Type' => 'text/html'}, '']
						end
					}
				when :put
					class_eval %{
						def PUT

						end
					}
				when :delete
					class_eval %{
						def DELETE
							[200, {}, '']
						end
					}
				end
			end
		end

	end

end
